package com.hanxiang.hankol.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.baselibrary.MessageBus;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.Config;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.ToastUtils;
import com.okhttp.callbacks.StringCallback;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    public static IWXAPI api;
    public static OnWxLoginCallBack mOnWxLoginCallBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Config.WECHAT_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(getIntent(), this);
    }

    public static void setWxLoginCallBack(OnWxLoginCallBack wxLoginCallBack) {
        mOnWxLoginCallBack = wxLoginCallBack;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onReq(BaseReq arg0) {
    }

    @Override
    public void onResp(BaseResp arg0) {
        if (arg0.getType() == 2) {
            if (arg0.errCode == 0) {
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(Config.wechat_share_success));
                finish();
                return;
            }
        }
        // getType 是 2 为分享动作
        if (arg0 instanceof SendAuth.Resp) {
            SendAuth.Resp resp = (SendAuth.Resp) arg0;
            if (resp.errCode != 0) {
                if (mOnWxLoginCallBack != null) {
                    mOnWxLoginCallBack.onLoginFail("授权取消");
                }
                finish();
            } else {
                WXManager.setCode(resp.code);
                WXManager.fetchToken(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (mOnWxLoginCallBack != null) {
                            mOnWxLoginCallBack.onLoginFail("授权信息失败");
                        }
                        finish();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {

                            JSONObject json = new JSONObject(response);
                            String errorCode = json.optString("errcode");
                            if (!CommonUtil.isBlank(errorCode)) {
                                ToastUtils.showShort(getApplicationContext(), "获取授权信息失败");
                                if (mOnWxLoginCallBack != null) {
                                    mOnWxLoginCallBack.onLoginFail("授权信息失败");
                                }
                            } else {
                                WXManager.setToken(json.optString("access_token"));
                                WXManager.setOpenid(json.optString("openid"));
                                WXManager.fetchWxUserInfo(json.optString("access_token"), json.optString("openid"), new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        if (mOnWxLoginCallBack != null) {
                                            mOnWxLoginCallBack.onLoginFail("授权信息失败");
                                        }
                                        finish();
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        try {
                                            JSONObject json = new JSONObject(response);
                                            WXManager.setAvatar(json.optString("headimgurl"));
                                            WXManager.setNickname(json.optString("nickname"));
                                            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(Config.wechat_get_token_success));
                                            if (mOnWxLoginCallBack != null) {
                                                mOnWxLoginCallBack.onLoginSuccess(json.optString("openid"),json.optString("headimgurl"),
                                                        json.optString("nickname"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        } catch (Exception e) {
                            if (mOnWxLoginCallBack != null) {
                                mOnWxLoginCallBack.onLoginFail("授权信息失败");
                            }
                            e.printStackTrace();
                        }
                        finish();
                    }
                });
            }
        }  if (arg0 instanceof WXLaunchMiniProgram.Resp) {
            WXLaunchMiniProgram.Resp resp = (WXLaunchMiniProgram.Resp) arg0;
            EventBusUtils.sendNotify1Value(MessageBus.msgId_wx_miniprogram_pay_success,resp.extMsg);
            finish();
        }else {
            finish();
        }
    }

    public interface OnWxLoginCallBack {
        void onLoginSuccess(String openid, String   headimgurl, String nickname);

        void onLoginFail(String mes);
    }

}

